package com.syxbyi.hmwk1.main;

import java.util.*;

/*
编程找出 1000 以内的所有完数并打印出来。 所谓完数就是一个数恰好等于它的因子之和，如：6=1＋2＋3
 */
public class PerfectNumbers {
    private int N = 1000;
    private final List<Integer> perfectNumbers = new ArrayList<>();

    public PerfectNumbers() {}

    public PerfectNumbers(int N) {
        this.N = N;
    }

    public List<Integer> getFactors(int num) {
        List<Integer> factors = new ArrayList<>();
        factors.add(1);
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                // 添加一对因数，如果一样则不重复
                factors.add(i);
                if (i != num / i) {
                    factors.add(num/i);
                }
            }
        }
        return factors;
    }

    public void findAllPerfectNumbers() {
        for (int i = 1; i < N; i++) {
            // 求因数
            List<Integer> factors = getFactors(i);
            // 求和
            int s = factors.stream().mapToInt(Integer::intValue).sum();
            if (i == s) {
                perfectNumbers.add(i);
            }
        }
    }

    @Override
    public String toString() {
        return perfectNumbers.toString();
    }

    public static void main(String[] args) {
        PerfectNumbers t = new PerfectNumbers();
        t.findAllPerfectNumbers();
        System.out.println(t);
    }
}
